"""
Case Type   : insert
Case Name   : insert，同一个表并发插入大量数据
Create At   : 2024/07/12
Owner       : songjing20
Description :
    1.创建表
    2.并发插入数据
    3.查询表数据
    4.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
History     :
"""

import os
import unittest

from yat.test import macro
from yat.test import Node
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant


class Pubsubclass(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.pri_node = Node(node='PrimaryDbUser')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.com_pub = Common()
        self.tb_name = 't_insert_0049'

    def test_pubsub(self):
        text = '-----step1:创建表;expect:成功-----'
        self.log.info(text)
        res = self.pri_sh.execut_db_sql(
            f"drop table if exists {self.tb_name} cascade;"
            f"create table {self.tb_name}(c1 int,c2 money);")
        self.log.info(res)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, res,
                      f'建表失败:{text}')

        text = '-----step2:并发插入数据;expect:成功-----'
        self.log.info(text)
        cmd = f'''source {macro.DB_ENV_PATH};
        for i in $(seq 1 10);do
            gsql -d {self.pri_node.db_name} -p {self.pri_node.db_port} \
            -c"insert into {self.tb_name} values(\
            generate_series(1,5000000),100);" &
        done;'''
        self.log.info(cmd)
        res = self.pri_node.sh(cmd).result()
        self.log.info(res)
        self.assertEqual(res.count(self.constant.INSERT_SUCCESS_MSG), 10,
                         f'执行失败:{text}')

        text = '-----step3:查询表数据;expect:-----'
        self.log.info(text)
        select_res = self.pri_sh.execut_db_sql(
            f"select count(*) from {self.tb_name};")
        self.log.info(select_res)
        self.assertIn('50000000', select_res, f'执行失败:{text}')

    def tearDown(self):
        text = '-----step4:清理环境;expect:成功-----'
        self.log.info(text)
        drop_res = self.pri_sh.execut_db_sql(
            f"drop table if exists {self.tb_name} cascade;")
        self.log.info(drop_res)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, drop_res,
                      f'删表失败:{text}')
        self.log.info(f"-----{os.path.basename(__file__)} end-----")
